/**
 * 
 */
package fr.toto.menuitem;

import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.nio.file.Path;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;

import com.kokotchy.betaSeriesAPI.model.Episode;

import fr.toto.constantes.Constantes;
import fr.toto.files.AccesFile;

/**
 * @author tshepo
 * 
 */
public class MyMenuItem extends JMenuItem implements Constantes {

	/**
	 * 
	 */
	private static final long serialVersionUID = -2714599161789323955L;
	private final Episode ep;

	/**
	 * @throws HeadlessException
	 */
	public MyMenuItem(Episode e, Path p) {
		super(p.toString());
		this.ep = e;

		if (!ep.isDownloaded())
			this.setEnabled(false);

		this.addMouseListener(new MouseAdapter() {
			@Override
			public void mousePressed(MouseEvent e) {
				if (e.getButton() != MouseEvent.BUTTON1) {
					JPopupMenu pm = makeMenu(ep);
					pm.setLocation(e.getLocationOnScreen());
					pm.setInvoker(pm);
					pm.setVisible(true);
				} else {
					if (ep.isDownloaded()) {
						Path file = AccesFile.Find(ep);
						if (file != null)
							AccesFile.Open(file);
					} else {
						if(configMenu.containsKey("0.item")) {
							String item = configMenu.getProperty("0.item");

							if (item.equals("SetWatched"))
								new SetWatchedMenuItem(ep).doClick();

							if (item.equals("WebSearch")) {
								String url = configMenu.getProperty("0.WebSearch.url");
								String format = configMenu.getProperty("0.WebSearch.format");
								new WebSearchMenuItem(ep, "", url, format).doClick();
							}
							if (item.equals("OpenDir"))
								new OpenDirMenuItem(ep).doClick();
							if (item.equals("BetaSeriesLink"))
								new BetaSeriesLinkMenuItem(ep).doClick();
						} else
						new WebSearchMenuItem(ep, "","").doClick();
					}
				}
			}
		});

	}

	private static JPopupMenu makeMenu(Episode ep) {
		JPopupMenu pm = new JPopupMenu();
		int i = 1;
		while (configMenu.containsKey(i + ".item")) {

			String item = configMenu.getProperty(i + ".item");

			if (item.equals("SetWatched"))
				pm.add(new SetWatchedMenuItem(ep));

			if (item.equals("WebSearch")) {
				String name = configMenu.getProperty(i + ".WebSearch.name");
				String url = configMenu.getProperty(i + ".WebSearch.url");
				String format = configMenu.getProperty(i + ".WebSearch.format");
				if (!name.isEmpty())
					pm.add(new WebSearchMenuItem(ep, name, url, format));
			}
			if (item.equals("OpenDir"))
				pm.add(new OpenDirMenuItem(ep));
			if (item.equals("BetaSeriesLink"))
				pm.add(new BetaSeriesLinkMenuItem(ep));
			if (item.equals("ArchiveSerie"))
				pm.add(new ArchiveSerieMenuItem(ep));

			i++;
		}

		return pm;

	}

}
